# 下载网易云音乐
from lxml import etree
import requests

import os

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}

# 网易云榜单页面
url = "https://music.163.com/discover/toplist?id=3778678"


def download_song(name, id, filepath):
    # 歌曲下载URL
    song_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'.format(id)
    print('正在下载歌曲： {}'.format(name))
    with open(filepath, 'wb') as f:
        f.write(requests.get(url=song_url, headers=headers).content)


def download_lyric(name, id, filepath):
    # 歌词下载路径
    lyric_url = 'http://music.163.com/api/song/lyric?id={}&lv=1&kv=1&tv=-1'.format(id)
    print('正在下载歌词: {}'.format(name))

    try:
        with open(filepath, 'w', encoding='utf8') as f:
            f.write(requests.get(url=lyric_url, headers=headers).json()['lrc']['lyric'])
    except Exception as e:
        print('歌词写入异常, name: {}, url is {}'.format(name, lyric_url))


re = requests.get(url=url, headers=headers).text
# 构造了一个XPath解析对象并对HTML文本进行自动修正
html = etree.HTML(re)

# XPath使用路径表达式来选取
x = html.xpath('//a[contains(@href,"/song?")]')

# 准备存放文件夹 文件夹不存在，则创建文件夹
save_path = './music'
folder = os.path.exists(save_path)
if not folder:
    os.makedirs(save_path)

# 对取到的数据进行筛选
for data in x:
    # 获取到音乐url
    href = data.xpath('./@href')[0]
    id = href.split("=")[1]
    href = 'http://music.163.com/song/media/outer/url?id={}.mp3'.format(id)
    # 添加到字典
    if "$" not in id:
        # 获得到标签内的文本（即音乐的名称）
        name = data.xpath('./text()')[0]
        # d[href] = name
        # 保存
        filepath = os.path.join(save_path, '{}.mp3'.format(name))
        lyric_path = os.path.join(save_path, '{}.lrc'.format(name))
        download_song(name, id, filepath)
        download_lyric(name, id, lyric_path)

